package com.zyw.boot.tool;

import com.google.gson.JsonObject;
import com.zyw.boot.tool.util.HttpUtil;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ExcelTranslator {

    // 科大讯飞翻译API配置（保持不变）
    private static final String APP_ID = "121636c7";
    private static final String API_KEY = "0743d202a408ddac65f0fed65ea158da";
    private static final String API_SECRET = "ZGY1NWNhZWI4ZGJiYzIxMjg4ODE5OTcz";
    private static final String API_URL = "https://ntrans.xfyun.cn/v2/ots";

    // 文件路径配置
    private static final String INPUT_FOLDER = "D:\\share\\tanslator";
    private static final String OUTPUT_FOLDER = "D:\\share\\tanslator_chinese";
    private static final String LOG_FOLDER = "D://log";

    // Excel列配置
    private static final int COL_ID = 0;
    private static final int COL_NAME = 1;
    private static final int COL_COMMENTS = 2;
    private static final int COL_NAME_ZH = 3;
    private static final int COL_COMMENTS_ZH = 4;

    private static final int THREAD_POOL_SIZE = 12;

    public static void main(String[] args) {
        createFolder(OUTPUT_FOLDER);
        createFolder(LOG_FOLDER);

        File folder = new File(INPUT_FOLDER);
        File[] files = folder.listFiles((dir, name) -> name.endsWith(".xlsx"));

        if (files == null || files.length == 0) {
            System.out.println("未找到Excel文件！");
            return;
        }

        ExecutorService executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
        List<Future<?>> futures = new ArrayList<>();
        for (File file : files) {
            futures.add(executor.submit(() -> {
            try {
                processExcelFile(file);
                System.out.println("文件 " + file.getName() + " 处理完成！");
            } catch (Exception e) {
                logError("处理文件 " + file.getName() + " 时出错: " + e.getMessage());
                e.printStackTrace();
            }
            }));
        }
    }

    private static void processExcelFile(File inputFile) throws Exception {
        try (InputStream is = new FileInputStream(inputFile);
             Workbook workbook = new XSSFWorkbook(is)) {

            Sheet sheet = workbook.getSheetAt(0);

            // 添加表头（如果不存在）
            Row headerRow = sheet.getRow(0);
            if (headerRow == null) headerRow = sheet.createRow(0);
            
            createCell(headerRow, COL_NAME_ZH, "name_chinese");
            createCell(headerRow, COL_COMMENTS_ZH, "comments_chinese");

            // 处理每一行数据
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (row == null) continue;

                // 获取原始内容
                String name = getCellValue(row.getCell(COL_NAME));
                String comments = getCellValue(row.getCell(COL_COMMENTS));

                // 翻译内容
                String translatedName = translateText(name);
                String translatedComments = translateText(comments);

                // 写入翻译结果
                createCell(row, COL_NAME_ZH, translatedName);
                createCell(row, COL_COMMENTS_ZH, translatedComments);
            }

            // 保存结果
            File outputFile = new File(OUTPUT_FOLDER, inputFile.getName());
            try (FileOutputStream fos = new FileOutputStream(outputFile)) {
                workbook.write(fos);
            }
        }
    }

    private static String getCellValue(Cell cell) {
        if (cell == null) return "";
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue().trim();
            case NUMERIC:
                return String.valueOf(cell.getNumericCellValue());
            default:
                return "";
        }
    }

    private static void createCell(Row row, int column, String value) {
        Cell cell = row.getCell(column);
        if (cell == null) {
            cell = row.createCell(column);
        }
        cell.setCellValue(value);
    }

    private static String translateText(String text) throws Exception {
        if (text == null || text.isEmpty()) return "";

        // 科大讯飞API调用（与原代码基本相同）
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
        String date = format.format(new Date());

        String body = buildHttpBody(text);
        String digestBase64 = "SHA-256=" + signBody(body);

        StringBuilder builder = new StringBuilder("host: ").append(new URL(API_URL).getHost()).append("\n")
                .append("date: ").append(date).append("\n")
                .append("POST ").append(new URL(API_URL).getPath()).append(" HTTP/1.1").append("\n")
                .append("digest: ").append(digestBase64);
        String sha = hmacsign(builder.toString(), API_SECRET);

        String authorization = String.format("api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", 
                API_KEY, "hmac-sha256", "host date request-line digest", sha);

        Map<String, String> header = new HashMap<>();
        header.put("Authorization", authorization);
        header.put("Content-Type", "application/json");
        header.put("Accept", "application/json,version=1.0");
        header.put("Host", new URL(API_URL).getHost());
        header.put("Date", date);
        header.put("Digest", digestBase64);

        Map<String, Object> resultMap = HttpUtil.doPost2(API_URL, header, body);
        if (resultMap != null && resultMap.containsKey("body")) {
            return parseTranslationResult(resultMap.get("body").toString());
        }
        return "翻译失败";
    }

    // 解析翻译结果
    private static String parseTranslationResult(String resultStr) {
        com.google.gson.JsonParser parser = new com.google.gson.JsonParser();
        com.google.gson.JsonObject resultJson = parser.parse(resultStr).getAsJsonObject();
        if (resultJson.has("data") && resultJson.get("data").isJsonObject()) {
            String dst = resultJson.getAsJsonObject("data").getAsJsonObject("result").getAsJsonObject("trans_result").get("dst").getAsString();

            return dst;
        }
        return "翻译失败";
    }

    // 组装http请求体
    private static String buildHttpBody(String text) throws Exception {
        JsonObject body = new JsonObject();
        JsonObject common = new JsonObject();
        JsonObject business = new JsonObject();
        JsonObject data = new JsonObject();

        // 填充common
        common.addProperty("app_id", APP_ID);

        // 填充business
        business.addProperty("from", "en"); // 源语言（假设为英文）
        business.addProperty("to", "zh"); // 目标语言

        // 填充data
        byte[] textByte = text.getBytes("UTF-8");
        String textBase64 = new String(Base64.getEncoder().encodeToString(textByte));
        data.addProperty("text", textBase64);

        // 填充body
        body.add("common", common);
        body.add("business", business);
        body.add("data", data);

        return body.toString();
    }

    // 对body进行SHA-256加密
    private static String signBody(String body) throws Exception {
        MessageDigest messageDigest;
        String encodestr = "";
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(body.getBytes("UTF-8"));
            encodestr = new String(Base64.getEncoder().encodeToString(messageDigest.digest()));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return encodestr;
    }

    // hmacsha256加密
    private static String hmacsign(String signature, String apiSecret) throws Exception {
        Charset charset = Charset.forName("UTF-8");
        javax.crypto.Mac mac = javax.crypto.Mac.getInstance("hmacsha256");
        javax.crypto.spec.SecretKeySpec spec = new javax.crypto.spec.SecretKeySpec(apiSecret.getBytes(charset), "hmacsha256");
        mac.init(spec);
        byte[] hexDigits = mac.doFinal(signature.getBytes(charset));
        return new String(Base64.getEncoder().encodeToString(hexDigits));
    }





    // 记录错误日志
    private static void logError(String message) {
        try {
            File logFile = new File(LOG_FOLDER, "translation_errors.log");
            try (PrintWriter writer = new PrintWriter(new FileOutputStream(logFile, true))) {
                writer.println(new Date() + " - " + message);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 创建文件夹
    private static void createFolder(String folderPath) {
        File folder = new File(folderPath);
        if (!folder.exists()) {
            folder.mkdirs();
        }
    }


}